"""
GDP动态柱状图开发
"""
from pyecharts.charts import Bar, Timeline
from pyecharts.options import LabelOpts, TitleOpts
from pyecharts.globals import ThemeType

# 读取文件中准备的数据
file_path = "/Users/dongjian/Documents/学习/python-learn-资料/资料/第1-12章资料/资料/可视化案例数据/动态柱状图数据/1960-2019全球GDP数据.csv"
f = open(file_path, "r", encoding="GB2312")
data_list = f.readlines()

# 关闭文件
f.close()
# 去掉第一行
data_list.pop(0)
data_dict = {}
# 读取数据
for line in data_list:
    split = line.split(",")
    year = int(split[0])
    country = split[1]
    gdp = float(split[2])
    try:
        data_dict[year].append([country, gdp])
    except KeyError as e:
        data_dict[year] = []
        data_dict[year].append([country, gdp])
# print(data_dict)

# 取出key并排序
sorted_year_list = data_dict.keys()
# 创建时间线对象
timeline = Timeline({"theme": ThemeType.LIGHT})
for year in sorted_year_list:
    # 对本年份的数据进行排序
    data_dict[year].sort(key=lambda element: element[1], reverse=True)
    # 通过切片取出本年份的前八
    year_data = data_dict[year][:8]
    x_data = []
    y_data = []
    for country_gdp in year_data:
        x_data.append(country_gdp[0])
        y_data.append(country_gdp[1] / 100000000)

    # 构建Bar()对象
    bar = Bar()
    x_data.reverse()
    y_data.reverse()
    bar.add_xaxis(x_data)
    bar.add_yaxis("GDP(亿)", y_data, label_opts=LabelOpts(position="right"))
    # xy轴反转
    bar.reversal_axis()
    # 设置标题
    bar.set_global_opts(
        title_opts=TitleOpts(title=f"{year}年全球前八国家GDP数据")
    )
    timeline.add(bar, str(year))

# 时间线变量设置

timeline.add_schema(
    play_interval=1000,
    is_timeline_show=True,
    is_auto_play=True,
    is_loop_play=False
)

# 绘图
timeline.render("1960~2019年全球GDP排名前八国家.html")
